package server;

import common.Tweet;

public class TagHandler implements Runnable {

	private TweetStack stack;
	private DispatcherList list;
	private String tag;
	private boolean finished;
	private Handler handler;

	public TagHandler(TweetStack stack, DispatcherInfo d, String tag, Handler h) {
		System.out.println("Some one created a Tag handler tag:  " + tag);
		this.stack = stack;
		this.list = new DispatcherList();
		list.add(d);
		this.tag = tag;
		this.finished = false;
		this.handler = h;

	}

	public boolean isAlive() {
		return !this.getFinished();
	}

	public synchronized boolean getFinished() {
		return this.finished;
	}

	public synchronized void setFinished(boolean b) {
		this.finished = b;
	}

	public String getTag() {
		return tag;
	}

	public DispatcherList getList() {
		return list;
	}

	public TweetStack getStack() {
		return stack;
	}

	public void removeDispatcher(Dispatcher d) {
		int size = list.size();
		for (int i = 0; i < size; i++) {
			if ((list.get(i)).getDispatcher() == d) {
				System.out.println("Removing doispatcher from the list");
				list.remove(i);
				break;
			}
		}
	}

	@Override
	public void run() {
		while (this.isAlive()) {
			if (list.isEmpty()) {
				this.setFinished(true);
			} else {
				if (stack.isEmpty()) {
					try {
						System.out.println("Taghandler " + tag + " list vazia");
						//Thread.sleep(10000);
						synchronized (stack){
							stack.wait();
						}
					} catch (InterruptedException e) {
						continue;
					}
				} else {
					DispatcherList intlist = new DispatcherList(list);
					int max = intlist.size();
					Tweet t = stack.pop();
					for (int i = 0; i < max; i++) {
						Dispatcher d = ((intlist.get(i)).getDispatcher());
						if (d.isAlive()) {
							System.out.println("Taghandler " + tag
									+ " sending Tweet " + t.getId()
									+ " sent to dispatcher " + d.getClientIP());
							((intlist.get(i)).getStack()).push(t);
						} else {
							System.out.println("A dispatcher is dead");
							this.removeDispatcher(d);
						}
					}
				}
			}
		}
	}

}
